import code from 'uview-ui/libs/config/props/code';
const $token = require('../utils/token');
const app = getApp();
const $invite = require('../utils/invite.js');
const $aes = require("../utils/aes.js");
const $config = require('../utils/config.js');
const GET = 'GET';
const POST = 'POST';
const PUT = 'PUT';
const FORM = 'FORM';
const DELETE = 'DELETE';

const envVersion = 'develop' //开发环境
// const envVersion = 'trial' //测试环境
// const envVersion = 'release' //正式环境

var url = '';
switch (envVersion) {
	case 'develop':
		// url = "http://bm.yundongshugen.com/hz/api" //新域名
		url = "http://bm.yundongshugen.com/api"
		break;
	case 'trial':
		url = "https://smhsw.lhs66666.com/api/" //测试环境
		// url = 'https://release.lhs66666.com/api/'; //预发布环境
		break;
	case 'release':
		url = 'https://smbjd.smhsw.com/api/';
		break;
	default:
		url = 'https://smbjd.smhsw.com/api/';
		break;
}
const baseURL = url;
export function getBaseUrl() {
	return baseURL;
}
export function request(url, data = {}, methodStr = 'GET', loading = true) {
	// var method = 'POST';
	var method = methodStr;

	// 如果是小程序页面 webview内嵌的h5页面进来的 携带的token 替换为当前页面的token，否则还是用回当前项目的token 参考baofu.js或者pagesA/baoFu/bindDetail/bindDetail 跟 selectType这些页面文件
	let user_token = localStorage.getItem("tokenValue"); //$token.get()

	if (loading) {
		// uni.showLoading({
		// 	title: '加载中',
		// 	icon: 'none',
		// 	mask: true
		// });
	}

	return new Promise(function(resolve, reject) {
		let accountInfo = "";
		// 应用程序版本号
		const systemInfo = uni.getSystemInfoSync()
		let appVersionName = ''
		// #ifdef APP-PLUS
		appVersionName = systemInfo.appWgtVersion;
		// #endif
		// #ifdef H5
		appVersionName = systemInfo.appVersion;
		// #endif
		let DefaultToken =
			'Bearer eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoyLCJvcmdhbml6YXRpb25faWQiOjUxLCJ1c2VyX2tleSI6IjVjYWY3NGRiLTlkMDAtNGFlOS1iMzYzLWRhNzIyNDg2NjcyMiIsImNvbnRlc3RfaWQiOjU4LCJ1c2VybmFtZSI6InJ5In0.vGRkzNkiJn7s5bqwns2SmUPM-DXWW5JKzxkxCXJXHETo1aFRFkszm1mXZZDItsnoT4b-CPeAfscTtiATxllHfQ'
		let header = {
			'content-type': 'application/json',
			// token: user_token,
			// Authorization: user_token  后面改回这个
			Authorization: user_token ? 'Bearer ' + user_token : DefaultToken
		};
		uni.request({
			url: baseURL + url,
			method: method,
			data: method === POST ? JSON.stringify(data) : data,
			header: header,
			complete: () => {},
			success(res) {
				let resData = res.data //.data
				if (res.statusCode == 500 && res.data.indexOf('未登录') != -1 && !$token.del()) {
					// console.log("未登录")
					$token.del();
					resolve(resData);
					return true;
				}

				if (loading) {
					uni.hideLoading({
						success: (res) => {}
					});
				}

				switch (res.data.code) {
					case 200:
						//正常请求
						resolve(resData);
						break;
					case 401:
						//未登录
						reject(res);
						$token.del();
						uni.showToast({
							title: '请重新登录',
							icon: 'none',
						});
						let pagePrevPath = localStorage.getItem("pagePrevPath");
						if (pagePrevPath) {} else {
							localStorage.clear();
						}
						setTimeout(() => {
							uni.navigateTo({
								url: '/pages/business/wxLogin'
							});
						}, 1500)
						break;
					case 400:
						//错误消息
						if (res.data.msg) {
							uni.showToast({
								title: res.data.msg || '网络异常',
								icon: 'none',
								duration: 2000
							});
						}
						reject(res.data.msg)
						break;
					case 4001:
						resolve(res.data.msg); // console.log(res)
						break;
					default:
						//其他请求失败
						if (res.data.msg) {
							uni.showToast({
								title: res.data.msg || '网络异常',
								icon: 'none',
								duration: 2000
							});
						}
						reject('运行时错误,请稍后再试');
						break;
				}
			},

			fail(err) {
				console.log(err);
				reject(err);
			}
		});
	});
}

// 上传文件到腾讯云
const COS = require('@/utils/cos-wx-sdk-v5.min.js')
const cos = new COS({
	SimpleUploadMethod: 'putObject',
	AppId: '1258084849',
	SecretId: 'AKIDtingfUXZqwrfPxLeqrhGQK4c0d199jeK',
	SecretKey: 'cyaw1YoqeBShiSu51jALZhYtW6RVIyRd'
})
export function uploadResource({
	url,
	file,
	fileName = 'file'
}) {
	let token = $token.get();
	return new Promise((resolve, reject) => {
		let nowDate = new Date()
		let date = {
			year: nowDate.getFullYear(),
			month: nowDate.getMonth() + 1,
			date: nowDate.getDate()
		}
		const systemTime = `${date.year}-${date.month}-${date.date}`
		let fileName2 = file.substr(file.lastIndexOf('/') + 1);
		cos.postObject({
				Bucket: 'smhs', // 存储桶
				Region: 'ap-nanjing', // 地域
				Key: 'smhswbjd/upload/' + systemTime + '/' + fileName2,
				FilePath: file,
			},
			function(err, data) {
				resolve({
					img_url: 'http://' + data.Location
				})
			})
	});
}